package com.magina.mq.rabbit.queue;

import com.magina.mq.constant.GloablFlag;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class RabQueueReceiver {

    @Value("${rab.queueName}")
    private String rabQueueName;

    @RabbitListener(queues = "${rab.queueName}")
    public void process(String msg, Channel channel , Message message) throws IOException {
        try {
            GloablFlag.flagCount.incrementAndGet();
            if (GloablFlag.flagCount.get() % 2 == 1) {
                String resultStr  = "RabbitMq:"+rabQueueName+" consumer 收到一条信息: " + msg;
                System.out.println(resultStr);
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } else {
                throw new RuntimeException("测试消费者抛出异常!");
            }
        } catch (Exception e) {
            String resultStr = "RabbitMq:" + rabQueueName + " consumer 收到一条信息: " + msg;
            System.out.println(resultStr + e.getMessage());
//            channel.basicReject(deliveryTag, false);
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false,false);//将消息继续放回队列等待消费
        }
    }
}
